package com.ruoyi.develop.payApply.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsSalebuyall.domain.GoodsSalebuyall;
import com.ruoyi.develop.goodsSalebuyall.service.IGoodsSalebuyallService;
import com.ruoyi.develop.lnZhaobiao.domain.LnZhaobiao;
import com.ruoyi.develop.lnZhaobiao.service.ILnZhaobiaoService;
import com.ruoyi.develop.lvBuy.domain.LvBuy;
import com.ruoyi.develop.lvBuy.service.ILvBuyService;
import com.ruoyi.develop.lvDaohuoDetail.domain.LvDaohuoDetail;
import com.ruoyi.develop.orderIronRecordBuy.domain.OrderIronRecordBuy;
import com.ruoyi.develop.orderIronRecordBuy.service.IOrderIronRecordBuyService;
import com.ruoyi.develop.payApplyBuy.domain.PayApplyBuy;
import com.ruoyi.develop.payApplyBuy.service.IPayApplyBuyService;
import com.ruoyi.develop.payApplyBuyDetail.domain.PayApplyBuyDetail;
import com.ruoyi.develop.payApplyBuyDetail.service.IPayApplyBuyDetailService;
import com.ruoyi.develop.process.processPayApply.service.IProcessPayApplyService;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.payApply.domain.PayApply;
import com.ruoyi.develop.payApply.service.IPayApplyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 付款申请单Controller
 *
 * @author lmm
 * @date 2024-10-09
 */
@RestController
@RequestMapping("/payApply/payApply")
public class PayApplyController extends BaseController {
    @Autowired
    private IPayApplyService payApplyService;
    @Autowired
    private ILvBuyService buyService;
    @Autowired
    private IPayApplyBuyService payApplyBuyService;
    @Autowired
    private IGoodsSalebuyallService goodsSalebuyallService;
    @Autowired
    private IPayApplyBuyDetailService payApplyBuyDetailService;
    @Autowired
    private ExportServiceImpl exportService;
    @Autowired
    private IProcessPayApplyService processPayApplyService;
    @Autowired
    private ILnZhaobiaoService lnZhaobiaoService;

    @Autowired
    private IOrderIronRecordBuyService orderIronRecordBuyService;


    /**
     * 查询付款申请单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:query')")
    @GetMapping("/list")
    public TableDataInfo list(PayApply entity) {
        startPage();
        List<PayApply> list = payApplyService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 查询付款申请单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:query')")
    @GetMapping("/selectListByBuy")
    public TableDataInfo selectListByBuy(PayApply entity) {
        startPage();
        List<PayApply> list = payApplyService.selectListByBuy(entity);
        return getDataTable(list);
    }


    @Log(title = "付款申请单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PayApply entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        List<PayApply> list = payApplyService.selectList(entity);
        list.stream().forEach(e -> {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("createTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getCreateTime()));
            e.setParams(map);
            if (e.getLvBuy() != null && StringUtils.isBlank(e.getLvBuy().getNos())) {
                String nos = payApplyBuyService.selectBuyNosByApplyId(e.getId());
                e.getLvBuy().setNos(nos);
            }
            map.put("type", DictUtils.getDictLabel("pay_apply_type", e.getType()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if (StringUtils.isBlank(fileName)) {
            fileName = "付款申请记录表.xlsx";
        }
        String templateName = "付款申请记录表.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }


    /**
     * 获取付款申请单详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(payApplyService.selectById(id));
    }

    /**
     * 获取付款申请单详细信息 -含运费
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:query')")
    @GetMapping(value = "/getWithShippingFee/{id}")
    public AjaxResult getWithShippingFee(@PathVariable("id") String id) {
        PayApply payApply = payApplyService.selectById(id);
        List<PayApplyBuyDetail> payApplyBuyDetailList = payApply.getPayApplyBuyDetailList();
        String buyIds = payApply.getBuyId();
        if (StringUtils.isNotBlank(buyIds)) {
            String[] splitBuyIds = buyIds.split(",");
            for (String buyId : splitBuyIds) {
                LvBuy lvBuy = buyService.selectById(buyId);
                if (lvBuy != null) {
                    if (BusinessConstants.STATUS_YES.equals(lvBuy.getDepositMerge())) {
                        PayApplyBuyDetail payApplyBuyDetail = new PayApplyBuyDetail();
                        payApplyBuyDetail.setGoodsName("运费");
                        GoodsSalebuyall buyDetail = new GoodsSalebuyall();
                        buyDetail.setGoodsBuyTotal(lvBuy.getShippingFee());
                        payApplyBuyDetail.setBuyDetail(buyDetail);
                        payApplyBuyDetail.setMoney(lvBuy.getShippingFee());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("buyNos", lvBuy.getNos());
                        payApplyBuyDetail.setParams(map);
                        payApplyBuyDetailList.add(payApplyBuyDetail);
                    }
                }
            }
        }
        return AjaxResult.success(payApply);
    }


    /**
     * 新增付款申请单
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:add')")
    @Log(title = "付款申请单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody PayApply entity) {
        int i = payApplyService.insert(entity);
        processPayApplyService.insertProcess(entity.getId(), "", "付款申请单提交申请");
        return toAjax(i);
    }


    /**
     * 新增付款申请单-定金
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:add')")
    @Log(title = "付款申请单-定金", businessType = BusinessType.INSERT)
    @PostMapping("/addForDeposit")
    public AjaxResult addForDeposit(@RequestBody PayApply entity) {
        // 先判断采购单 付款状态 和 金额
        if (StringUtils.isNotBlank(entity.getBuyId())) {
            LvBuy lvBuy = buyService.selectById(entity.getBuyId());
            if (lvBuy == null) {
                return AjaxResult.error("采购单不存在");
            }
            if (BusinessConstants.BUY_PAY_STATUS_DEPOSIT_APPLY.equals(lvBuy.getPayApplyState())
                    || BusinessConstants.BUY_PAY_STATUS_PAID.equals(lvBuy.getPayApplyState())) {
                return AjaxResult.error("采购单已申请付定金或已付款!");
            }
            // 付款金额是否超过 采购单金额
            if (lvBuy.getPayApplyTotalMoney().add(entity.getTotalMoney()).compareTo(lvBuy.getMoney()) > 0) {
                return AjaxResult.error("付款金额不能超过采购单金额!");
            }
        }

        int i = payApplyService.addForDeposit(entity);
        if (i > 0) {
            return AjaxResult.success("新增付款申请单成功");
        } else {
            return AjaxResult.error("新增付款申请单失败");
        }
    }


    /**
     * 新增付款申请单-运费
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:add')")
    @Log(title = "付款申请单-运费", businessType = BusinessType.INSERT)
    @PostMapping("/addForShippingFee")
    public AjaxResult addForShippingFee(@RequestBody PayApply entity) {
        int i = payApplyService.addForShippingFee(entity);
        if (i > 0) {
            return AjaxResult.success("新增付款申请单成功");
        } else {
            return AjaxResult.error("新增付款申请单失败");
        }
    }


    /**
     * 新增付款申请单-招投标
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:add')")
    @Log(title = "付款申请单-运费", businessType = BusinessType.INSERT)
    @PostMapping("/addForBid")
    public AjaxResult addForBid(@RequestBody PayApply entity) {
        int i = payApplyService.addForBid(entity);
        processPayApplyService.insertProcess(entity.getId(), "", "提交付款申请单");
        if (i > 0) {
            return AjaxResult.success("新增付款申请单成功");
        } else {
            return AjaxResult.error("新增付款申请单失败");
        }
    }


    /**
     * 统一付款申请单
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:add')")
    @Log(title = "统一付款申请单", businessType = BusinessType.INSERT)
    @PostMapping("/addForUnion")
    public AjaxResult addForUnion(@RequestBody PayApply entity) {
        // 先判断采购单 付款状态 和 金额
        if (StringUtils.isNotBlank(entity.getBuyId())) {
            LvBuy lvBuy = buyService.selectById(entity.getBuyId());
            if (lvBuy == null) {
                return AjaxResult.error("采购单不存在");
            }
            if (BusinessConstants.BUY_PAY_STATUS_ALL_APPLY.equals(lvBuy.getPayApplyState())
                    || BusinessConstants.BUY_PAY_STATUS_PAID.equals(lvBuy.getPayApplyState())) {
                return AjaxResult.error("采购单已全部申请付款或已付款!");
            }
            // 付款金额是否超过 采购单金额
            // 运费合并付款
            if (BusinessConstants.STATUS_YES.equals(lvBuy.getDepositMerge())) {
                if (lvBuy.getPayApplyTotalMoney().add(entity.getTotalMoney()).compareTo(lvBuy.getMoney().add(lvBuy.getShippingFee())) > 0) {
                    return AjaxResult.error("付款金额不能超过采购单金额!");
                }
            }
            if (BusinessConstants.STATUS_NO.equals(lvBuy.getDepositMerge())) {
                if (lvBuy.getPayApplyTotalMoney().add(entity.getTotalMoney()).compareTo(lvBuy.getMoney()) > 0) {
                    return AjaxResult.error("付款金额不能超过采购单金额!");
                }
            }

        }
        int i = payApplyService.addForUnion(entity);
        processPayApplyService.insertProcess(entity.getId(), "", "提交付款申请单");
        if (i > 0) {
            return AjaxResult.success("新增付款申请单成功");
        } else {
            return AjaxResult.error("新增付款申请单失败");
        }
    }


    /**
     * 铁件采购的付款单
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:add')")
    @Log(title = "统一付款申请单", businessType = BusinessType.INSERT)
    @PostMapping("/addForIron")
    public AjaxResult addForIron(@RequestBody PayApply entity) {
        int i = payApplyService.addForIron(entity);
        processPayApplyService.insertProcess(entity.getId(), "", "提交付款申请单");
        if (i > 0) {
            return AjaxResult.success("新增铁件付款申请单成功");
        } else {
            return AjaxResult.error("新增铁件付款申请单失败");
        }
    }


    /**
     * 新增付款申请单-订单合并付款
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:add')")
    @Log(title = "付款申请单-订单合并付款", businessType = BusinessType.INSERT)
    @PostMapping("/addForBuyList")
    public AjaxResult addForBuyList(@RequestBody PayApply entity) {

        int i = payApplyService.addForBuyList(entity);
        processPayApplyService.insertProcess(entity.getId(), "", "提交付款申请单");
        if (i > 0) {
            return AjaxResult.success("新增付款申请单成功");
        } else {
            return AjaxResult.error("新增付款申请单失败");
        }
    }


    /**
     * 修改付款申请单
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:edit')")
    @Log(title = "付款申请单", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody PayApply entity) {
        return toAjax(payApplyService.update(entity));
    }


    /**
     * 取消申请单
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:query')")
    @GetMapping(value = "cancel/{id}")
    @Transactional
    public AjaxResult cancel(@PathVariable("id") String id) {
        PayApply entity = payApplyService.selectById(id);
        if (entity == null) {
            return AjaxResult.error("申请单不存在");
        }

        if (!(BusinessConstants.PAY_APPLY_ASSESS_STATUS_UN.equals(entity.getAssessStatus()) || BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_REJECT.equals(entity.getAssessStatus()))) {
            return AjaxResult.error("申请单状态不是未审计 和 审计退回状态，不能撤销");
        }
        // 如果是 标书费付款
        if (BusinessConstants.PAY_APPLY_CATEGORY_BOND.equals(entity.getCategory())
                || BusinessConstants.PAY_APPLY_CATEGORY_SERVICE.equals(entity.getCategory())
                || BusinessConstants.PAY_APPLY_CATEGORY_BOOK.equals(entity.getCategory())) {
            LnZhaobiao lnZhaobiao = lnZhaobiaoService.selectById(entity.getBidId());
            if (BusinessConstants.PAY_APPLY_CATEGORY_BOND.equals(entity.getCategory())) {
                lnZhaobiao.setBondStatus(BusinessConstants.STATUS_NO);

            }
            if (BusinessConstants.PAY_APPLY_CATEGORY_SERVICE.equals(entity.getCategory())) {
                lnZhaobiao.setServiceStatus(BusinessConstants.STATUS_NO);
            }
            if (BusinessConstants.PAY_APPLY_CATEGORY_BOOK.equals(entity.getCategory())) {
                lnZhaobiao.setBookStatus(BusinessConstants.STATUS_NO);
            }
            lnZhaobiaoService.update(lnZhaobiao);
        }

        // 如果是 铁件采购
        if (BusinessConstants.PAY_APPLY_CATEGORY_BUY_IRON.equals(entity.getCategory())) {
            LvBuy lvBuy = buyService.selectById(entity.getBuyId());
            lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_ALL_REJECT);
            lvBuy.setPayApplyTotalMoney(lvBuy.getPayApplyTotalMoney().subtract(entity.getTotalMoney()));
            lvBuy.setPayApplyRemainMoney(lvBuy.getPayApplyRemainMoney().add(entity.getTotalMoney()));
            buyService.update(lvBuy);
        }


        // 如果是 普通采购 和 运费
        if (BusinessConstants.PAY_APPLY_CATEGORY_BUY_COMMON.equals(entity.getCategory())
                || BusinessConstants.PAY_APPLY_CATEGORY_SHIPPING.equals(entity.getCategory())) {

            // 如果是合并付款 查出付款的所有采购单，并退回
            if (BusinessConstants.PAY_APPLY_TYPE_SUM.equals(entity.getType())) {
                PayApplyBuy payApplyBuy = new PayApplyBuy();
                payApplyBuy.setApplyId(id);
                List<PayApplyBuy> applyBuyList = payApplyBuyService.selectList(payApplyBuy);
                for (PayApplyBuy applyBuy : applyBuyList) {
                    // 修改采购单状态  如果是合并付款   TODO 合并付款 包含 付定金 尾款 全款情况
                    LvBuy lvBuy = buyService.selectById(applyBuy.getBuyId());
                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_ALL_REJECT);
                    lvBuy.setPayApplyTotalMoney(lvBuy.getPayApplyTotalMoney().subtract(applyBuy.getApplyMoney()));
                    lvBuy.setPayApplyRemainMoney(lvBuy.getPayApplyRemainMoney().add(applyBuy.getApplyMoney()));
                    buyService.update(lvBuy);
                }
            } else if (BusinessConstants.PAY_APPLY_CATEGORY_SHIPPING.equals(entity.getCategory())) {
                // 如果是 退回的运费
                LvBuy lvBuy = buyService.selectById(entity.getBuyId());
                lvBuy.setShippingStatus(BusinessConstants.BUY_PAY_SHIPPING_REJECT);
                lvBuy.setShippingFeeRemain(lvBuy.getShippingFeeRemain().add(entity.getTotalMoney()));
                buyService.update(lvBuy);
            } else {
                // 如果是单个的采购单
                LvBuy lvBuy = buyService.selectById(entity.getBuyId());
                if (BusinessConstants.PAY_APPLY_TYPE_DEPOSIT.equals(entity.getType())) {
                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_DEPOSIT_REJECT);
                }
                if (BusinessConstants.PAY_APPLY_TYPE_PART.equals(entity.getType())) {
                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PART_REJECT);
                }
                if (BusinessConstants.PAY_APPLY_TYPE_ALL.equals(entity.getType())) {
                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_ALL_REJECT);
                }
                lvBuy.setPayApplyTotalMoney(lvBuy.getPayApplyTotalMoney().subtract(entity.getTotalMoney()));
                lvBuy.setPayApplyRemainMoney(lvBuy.getPayApplyRemainMoney().add(entity.getTotalMoney()));
                buyService.update(lvBuy);
            }
            // 修改采购单明细 申请付款金额
            PayApplyBuyDetail payApplyBuyDetail = new PayApplyBuyDetail();
            payApplyBuyDetail.setPayApplyId(id);
            List<PayApplyBuyDetail> detailList = payApplyBuyDetailService.selectList(payApplyBuyDetail);
            for (PayApplyBuyDetail detail : detailList) {
                // 修改采购单明细状态
                GoodsSalebuyall goodsSalebuyall = goodsSalebuyallService.selectById(detail.getBuyDetailId());
                goodsSalebuyall.setApplyRemain(goodsSalebuyall.getApplyRemain().add(detail.getMoney()));
                goodsSalebuyall.setApplyMoney(goodsSalebuyall.getApplyMoney().subtract(detail.getMoney()));
                goodsSalebuyallService.update(goodsSalebuyall);
            }

        }


        entity.setAssessStatus(BusinessConstants.PAY_APPLY_ASSESS_STATUS_CANCEL);
        entity.setDelFlag(BusinessConstants.DEL_FLAG_YES);
        processPayApplyService.insertProcess(entity.getId(), "", "取消付款申请单");
        return AjaxResult.success(payApplyService.update(entity));
    }


    /**
     * 审计
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:edit')")
    @Log(title = "付款申请单审计", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody PayApply entity) {
        // 先查询一下申请单状态 审计只能审计待审计状态
        PayApply payApply = payApplyService.selectById(entity.getId());
        if (payApply == null) {
            return AjaxResult.error("申请单不存在");
        }
        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_PASS.equals(payApply.getAssessStatus())) {
            return AjaxResult.error("付款申请单已经审计通过，请核对！");
        }
        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_REJECT.equals(payApply.getAssessStatus())) {
            return AjaxResult.error("付款申请单已经审计退回，请核对！");
        }

        if (!(BusinessConstants.PAY_APPLY_ASSESS_STATUS_UN.equals(payApply.getAssessStatus())
                || BusinessConstants.PAY_APPLY_ASSESS_STATUS_REJECT.equals(payApply.getAssessStatus()))) {
            return AjaxResult.error("付款申请单状态异常，请核对！");
        }

        entity.setAuditTime(DateUtils.getNowDate());
        entity.setAuditBy(SecurityUtils.getUsername());
        entity.setAssessTime(null);
        entity.setAssessOpinion("");
        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_REJECT.equals(entity.getAssessStatus())) {
            processPayApplyService.insertProcess(entity.getId(), "", "审计退回");
        }
        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_PASS.equals(entity.getAssessStatus())) {
            processPayApplyService.insertProcess(entity.getId(), "", "审计通过");
        }
        return toAjax(payApplyService.update(entity));
    }

    /**
     * 批量审计
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:edit')")
    @Log(title = "付款申请单批量终审", businessType = BusinessType.UPDATE)
    @PostMapping("/auditBatch")
    public AjaxResult auditBatch(HttpServletRequest request) {
        String[] ids = request.getParameter("ids").split(",");
        String assessStatus = request.getParameter("assessStatus");
        String assessOpinion = request.getParameter("assessOpinion");
        List<PayApply> applyList = new ArrayList<>();
        for (String id : ids) {
            PayApply entity = payApplyService.selectById(id);
            if (entity == null) {
                return AjaxResult.error("申请单不存在");
            }
            if (!(BusinessConstants.PAY_APPLY_ASSESS_STATUS_UN.equals(entity.getAssessStatus())
                    || BusinessConstants.PAY_APPLY_ASSESS_STATUS_REJECT.equals(entity.getAssessStatus()))) {
                return AjaxResult.error("付款申请单:" + entity.getNos() + "状态异常，请核对！");
            }
            applyList.add(entity);
        }
        for (PayApply entity : applyList) {
            entity.setAuditTime(DateUtils.getNowDate());
            entity.setAuditBy(SecurityUtils.getUsername());
            entity.setAssessTime(DateUtils.getNowDate());
            entity.setAssessOpinion(assessOpinion);
            entity.setAssessStatus(assessStatus);
            if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_REJECT.equals(assessStatus)) {
                processPayApplyService.insertProcess(entity.getId(), "", "审计退回");
            }
            if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_PASS.equals(assessStatus)) {
                processPayApplyService.insertProcess(entity.getId(), "", "审计通过");
            }
            payApplyService.update(entity);
        }
        return toAjax(1);
    }


    /**
     * 终审
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:edit')")
    @Log(title = "付款申请单终审", businessType = BusinessType.UPDATE)
    @PutMapping("/assess")
    public AjaxResult assess(@RequestBody PayApply entity) {
        // 先查询一下申请单状态 审计只能审计待审计状态
        PayApply payApply = payApplyService.selectById(entity.getId());
        if (payApply == null) {
            return AjaxResult.error("申请单不存在");
        }
        // 在付款之前 终审通过的可以再次退回
//        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_PASS.equals(payApply.getAssessStatus())) {
//            return AjaxResult.error("付款申请单已经终审通过，请核对！");
//        }
        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_REJECT.equals(payApply.getAssessStatus())) {
            return AjaxResult.error("付款申请单已经终审退回，请核对！");
        }
        if (!(BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_PASS.equals(payApply.getAssessStatus())
                || BusinessConstants.PAY_APPLY_ASSESS_STATUS_REJECT.equals(payApply.getAssessStatus())
                || BusinessConstants.PAY_APPLY_ASSESS_STATUS_PASS.equals(payApply.getAssessStatus())
        )) {
            return AjaxResult.error("付款申请单状态异常，请核对！");
        }
        entity.setAssessTime(DateUtils.getNowDate());
        entity.setAssessBy(SecurityUtils.getUsername());
        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_REJECT.equals(entity.getAssessStatus())) {
            if(!BusinessConstants.PAY_APPLY_PAY_STATUS_UN.equals(payApply.getPayStatus())){
                return AjaxResult.error("付款申请已经付款，不能退回！");
            }
            processPayApplyService.insertProcess(entity.getId(), "", "终审退回");
        }
        if (BusinessConstants.PAY_APPLY_ASSESS_STATUS_PASS.equals(entity.getAssessStatus())) {
            processPayApplyService.insertProcess(entity.getId(), "", "终审通过");
        }
        return toAjax(payApplyService.update(entity));
    }

    /**
     * 批量终审
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:edit')")
    @Log(title = "付款申请单批量终审", businessType = BusinessType.UPDATE)
    @PostMapping("/assessBatch")
    public AjaxResult assessBatch(HttpServletRequest request) {

        String[] ids = request.getParameter("ids").split(",");
        String assessStatus = request.getParameter("assessStatus");
        String assessOpinion = request.getParameter("assessOpinion");

        for (String id : ids) {
            PayApply entity = payApplyService.selectById(id);
            if (entity == null) {
                return AjaxResult.error("申请单不存在");
            }
            entity.setAssessTime(DateUtils.getNowDate());
            entity.setAssessStatus(assessStatus);
            entity.setAssessOpinion(assessOpinion);
            entity.setAssessBy(SecurityUtils.getUsername());
            processPayApplyService.insertProcess(entity.getId(), "", "终审付款申请单");
            payApplyService.update(entity);
        }
        return toAjax(1);
    }


    /**
     * 删除付款申请单
     */
    @PreAuthorize("@ss.hasPermi('develop:PayApply:remove')")
    @Log(title = "付款申请单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(payApplyService.deleteByIds(ids));
    }


    /**
     * 根据付款金额 生成 付款单 明细列表
     */
    @GetMapping("/generateMoneyList")
    public AjaxResult generateMoneyList(PayApply entity) {
        List<PayApplyBuyDetail> payApplyBuyDetailList = payApplyService.selectPayApplyBuyDetailList(null, entity.getBuyId(), entity.getTotalMoney());
        return AjaxResult.success(payApplyBuyDetailList);
    }


    /**
     * 批量合并上传发票
     */
    @Log(title = "批量上传发票", businessType = BusinessType.INSERT)
    @PostMapping("/batchUploadInvoice")
    public AjaxResult batchUploadInvoice(@RequestBody PayApply entity) {
        String[] ids = entity.getIds().split(",");
        if (ids == null || ids.length == 0) {
            return AjaxResult.error("请选择要上传发票的申请单");
        }
        for (String id : ids) {
            PayApply payApply = payApplyService.selectById(id);
            payApply.setIsInvoice(BusinessConstants.STATUS_YES);
            payApply.setInvoiceCode(entity.getInvoiceCode());
            payApply.setInvoicePhoto(entity.getInvoicePhoto());
            payApplyService.update(payApply);
        }
        return AjaxResult.success("批量上传发票成功！");
    }

}
